<?php

class FirmsController extends AdminController {


	public function actionView($id) {
		$this->render('view', array(
			'model' => $this->loadModel($id, 'Firms'),
		));
	}
	
	public function actionCreate() {
		$model = new Firms;

		if (isset($_POST['Firms'])) {
            if (isset($_POST['Firms']['logo']) && '' == $_POST['Firms']['logo']) unset($_POST['Firms']['logo']);
			$model->setAttributes($_POST['Firms']);
			$firmTmpl = FirmTmpls::model()->findbyPk($model->firm_tmpl_id);
			$now = time();
			$model->start_date = $now;
			$enddate = 0;
			if (1 == $model->processed) {    
				$enddate = $this->getLifeTimeInterval($firmTmpl->life_time);
			} else {
				$enddate = $this->getLifeTimeInterval($firmTmpl->trial_time);
			}
			$model->end_date = $now + $enddate;
			$model->rating_order = intval($firmTmpl->rating_score); 
			if (1 == $model->active) {
				$model->activated_by = Yii::app()->user->id;
			}
			$model->author_id = Yii::app()->user->id;
            
            $old_img_name = $model->logo;
            $upload_data = $this->uploadFirmImg($model, 'logo');
            $model->logo = $upload_data['img_name'];
            $resize = $upload_data['success'];            
            
			if ($model->save()) {
				if ($resize) {
                    $this->resizeFirmImg($model->logo, array('firms_img_logo' => array('w'=>$this->getYiiP('firms_logo_w'), 'h'=>$this->getYiiP('firms_logo_h'))) );
				}            
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		$model = $this->loadModel($id, 'Firms');
		if (isset($_POST['Firms'])) {
            //removing empty logo field
            if (isset($_POST['Firms']['logo']) && '' == $_POST['Firms']['logo']) unset($_POST['Firms']['logo']);
        
			$old_processed = $model->processed;
			$old_activated = $model->active;
			$old_firm_tmpl_id = $model->firm_tmpl_id;
			
			
			
			$model->setAttributes($_POST['Firms']);
			$firmTmpl = FirmTmpls::model()->findbyPk($model->firm_tmpl_id);
			$model->rating_order = intval($firmTmpl->rating_score);
			
			
			if ($old_activated != $model->active && 1 == $model->active) {
				$model->activated_by =  Yii::app()->user->id;
			}
			
			$now = time();
			$enddate = 0;
			
			if (($old_processed != $model->processed) || $old_firm_tmpl_id != $model->firm_tmpl_id) {
				if (1 == $model->processed) {
					$enddate = $this->getLifeTimeInterval($firmTmpl->life_time);
				} else {
					$enddate = $this->getLifeTimeInterval($firmTmpl->trial_time);
				}
				$model->rating_order = intval($firmTmpl->rating_score);
				$model->start_date = $now;
				$model->end_date = $now + $enddate;
			}
            
			/*
            $NewLogo = CUploadedFile::getInstance($model,'logo');
            $bResize = false;
            if ($NewLogo) {
                $old_img = $model->logo;
                $model->logo = $NewLogo;
                if ($model->validate(array('logo'))) {
                    $new_img_name = $this->generateImgName().'.'.$NewLogo->getExtensionName();
                    $new_img_orig_path = $this->getRealImgDir(Yii::app()->params['firms_img_orig'].$this->getImgPathPart($new_img_name));
                    if ($new_img_orig_path) {
                        if ($NewLogo->saveAs($new_img_orig_path.$new_img_name)) {
                            $model->logo = $new_img_name;
                        } else {
                            $model->logo = $old_img;
                        }
                    } else {
                       $model->logo = $old_img; 
                    }
                } else {
                    $model->logo = $old_img;
                }
            }
            */
            
            $old_img_name = $model->logo;
            $upload_data = $this->uploadFirmImg($model, 'logo');
            $model->logo = $upload_data['img_name'];
            $resize = $upload_data['success'];
            
			if ($model->save()) {
				if ($resize) {
                    $this->resizeFirmImg($model->logo, array(
                        'firms_img_logo' => array('w'=>$this->getYiiP('firms_logo_w'), 'h'=>$this->getYiiP('firms_logo_h')),
//                        'firms_img_mid' => array('w'=>$this->getYiiP('firms_mid_w'), 'h'=>$this->getYiiP('firms_mid_h')),
//                        'firms_img_thumb' => array('w'=>$this->getYiiP('firms_thumb_w'), 'h'=>$this->getYiiP('firms_thumb_h'))
                        )
                    );
				}	            
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			$model = $this->loadModel($id, 'Firms');
            // $this->deleteLogo($model->logo);
            // $model->delete();
			$model->deleted = 1;
			if ($model->save()) {
				if (!Yii::app()->getRequest()->getIsAjaxRequest()) $this->redirect(array('admin'));
			}	
		} else
			throw new CHttpException(400, AdminModule::t('Некорректный запрос.'));
	}

	public function actionDeleteLogo() {
		if (!Yii::app()->getRequest()->getIsAjaxRequest()) $this->redirect(array('admin'));
		$record_id = intval(CHttpRequest::getParam('id'));
		if (0 >= $record_id) $this->ajax_responce('error:record_id');
        $model = $this->loadModel($record_id, 'Firms');
		if (!$this->deleteLogo($model->logo)) $this->ajax_responce('error:deleting');
        $model->logo = '';
        $model->save();
		return $this->ajax_responce('success');
	}	    
    
	protected function deleteLogo($logo) {
        if ('' == $logo) return false;
        @unlink($this->getFirmImgSrc($logo, 'firms_img_logo', 'real'));
		@unlink($this->getFirmImgSrc($logo, 'firms_img_orig', 'real'));
		return true;
	}    
    
    
	public function actionIndex() {
		$dataProvider = new CActiveDataProvider('Firms');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		$model = new Firms('search');
		$model->unsetAttributes();
		$model->deleted = 0;
		if (isset($_GET['Firms']))
			$model->setAttributes($_GET['Firms']);

		$this->render('admin', array(
			'model' => $model,
		));
	}

}